package fr.insta.reverse.uml.java.projectParser;

import java.util.ArrayList;

import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;

public class ReverseClass
{

	public ArrayList<String> generateClassUmlCode(JavaClass jc)
	{
		ArrayList<String> buff = new ArrayList<String>();
		StringBuffer sb = new StringBuffer();
		// on commence par créer la classe avec les proprietes et les methodes
		jc.getFields();
		jc.getMethods();

		if (jc.getFields().length == 0 && jc.getMethods().length == 0)
		{
			buff.add("[" + jc.getClassName() + "]");
		}
		else
		{
			sb.append("[" + jc.getClassName() + "|");
			Field[] att = jc.getFields();
			Method[] met = jc.getMethods();
			//jc.get

			//properties
			for (int i = 0; i < att.length; i++)
			{
				if (i > 0)
				{
					sb.append(";");
				}

				// recuperation premier caractere
				String init = att[i].getSignature().substring(0, 1);

				if (init.equals("L"))
				{
					int ref = att[i].getSignature().lastIndexOf("/");

					if (ref == -1)
					{
						ref = 0;
					}

					sb.append(att[i].getSignature().substring(ref + 1).replace(";", "") + " ");
				}
				else if (init.equals("I"))
				{
					sb.append("Int ");
				}
				else if (init.equals("B"))
				{
					sb.append("Byte ");
				}
				else if (init.equals("C"))
				{
					sb.append("Char ");
				}
				else if (init.equals("F"))
				{
					sb.append("Float ");
				}
				else if (init.equals("J"))
				{
					sb.append("Long ");
				}
				else if (init.equals("S"))
				{
					sb.append("Short ");
				}
				else if (init.equals("B"))
				{
					sb.append("boolean ");
				}
				else if (init.equals("["))
				{
					sb.append("Array() ");
				}

				sb.append(att[i].getName());
			}
			sb.append("|");

			//methods
			for (int i = 0; i < jc.getMethods().length; i++)
			{
				if (!met[i].getName().equals("<init>"))
				{
					sb.append(met[i].getName() + "();");
				}
			}
			sb.append("]");
			buff.add(sb.toString());
			sb = new StringBuffer();
		}

		//example exit :  [User|+Forename+;Surname;+HashedPassword;-Salt|+Login();+Logout()]

		//ajout de l'heritage
		//example [Wages]^-[Salaried]
		if (!jc.getSuperclassName().equals("java.lang.Object"))
		{
			buff.add("[" + jc.getSuperclassName() + "]^-[" + jc.getClassName() + "]");
		}

		// ajout des interfaces
		//example  [<<ITask>>]^-.-[NightlyBillingTask]
		if (!(jc.getInterfaceNames().length == 0))
		{
			String[] interf = jc.getInterfaceNames();
			for (int i = 0; i < interf.length; i++)
			{
				String cache = interf[i];
				buff.add("[<<" + cache + ">>]^-.-[" + jc.getClassName() + "]");
			}
		}

		return buff;
	}
}
